"ui";
let deviceWidth = device.width;
let deviceHeight = device.height;

let margin = parseInt(deviceWidth * 0.05);
let buttonWidth = parseInt(deviceWidth * 0.45);

let rootPath = "./";

let isLogin = 0;
let mobile = ""
run();
ui.statusBarColor("#000000");

function buildId() {
    return device.buildId;
}

toastLog("设备的 Android ID: " + buildId());

files.write( rootPath + "float.txt", "");


//显示登录界面
function showLoginUI(){
    ui.layout(
      <frame>
        <vertical h="auto" align="center" margin="0 50">
          <linear>
             <text w="56" gravity="center" color="#111111" size="16">手机</text>
             <input id="mobile" w="*" h="40"/>
          </linear>
          <linear>
             <text w="56" gravity="center" color="#111111" size="16">密码</text>
             <input id="password" w="*" h="40" password="true"/>
          </linear>
          <linear gravity="center">
             <button id="login" text="登录"/>
             <button id="register" text="注册"/>
          </linear>
        </vertical>
      </frame>
    );

    ui.login.on("click", () => {
        const postData = { mobile: ui.mobile.text(), pwd: ui.password.text(),buildId:buildId() };
        var url = "https://anauto.millsecond.cn/api/user/login";
        r = http.postJson(url, postData);
        var result = r.body.json();
        if(result.code == 200){
            toast("登录成功");
            mobile = ui.mobile.text();
            let filePath = rootPath + "config.txt";
            files.write(filePath, "");
            files.write(filePath, mobile);
            isLogin = 1
            showUI();
        }else{
            toast("登录失败");
        }
    });
    ui.register.on("click", () => showRegisterUI());
}

//显示注册界面
function showRegisterUI(){
    ui.layout(
      <frame>
        <vertical h="auto" align="center" margin="0 50">
          <linear>
             <text w="56" gravity="center" color="#111111" size="16">手机</text>
             <input id="mobile" w="*" h="40"/>
          </linear>
          <linear>
             <text w="56" gravity="center" color="#111111" size="16">密码</text>
             <input id="password" w="*" h="40" password="true"/>
          </linear>
          <linear>
             <text w="56" gravity="center" color="#111111" size="16">用户名</text>
             <input id="name" w="*" h="40" />
          </linear>
          <linear gravity="center">
             <button id = "sure">确定</button>
             <button id="cancel">取消</button>
          </linear>
        </vertical>
      </frame>
    );
    ui.cancel.on("click", () => showLoginUI());
    ui.sure.on("click", () => {
       const postData = { nickname: ui.name.text(), pwd: ui.password.text(), mobile: ui.mobile.text(),buildId:buildId() };
        var url = "https://anauto.millsecond.cn/api/user/register";
        r = http.postJson(url, postData);
        var result = r.body.json();
        if(result.code == 200){
            toast("注册成功，请登录");
            showLoginUI();
        }else{
            toast("注册失败");
        }

    }); 
}

function showUI(){
    ui.layout(
        <frame>
            <vertical>
                <appbar>
                    <toolbar id={"toolbar"} title="Agro-自动交易"/>
                </appbar>

                <horizontal margin={margin + "px"}>
                    <button id={"about1"} text={"使用须知"} width={buttonWidth + "px"}/>
                    <button id={"about2"} text={"更新说明"} width={buttonWidth + "px"}/>
                </horizontal>
        
        
                <horizontal margin={margin + "px"}>
                    <vertical>
                        <button id={"showFloatingTB"} text={"加载悬浮窗"} width={buttonWidth + "px"}/>
                        <button id={"clearTB"} text={"清除旧版本"} width={buttonWidth + "px"}/>
                    </vertical>
                    <vertical>
                        <button id={"openTB"} text={"转到Agro"} width={buttonWidth + "px"}/>
                        <button id={"updateTB"} text={"获取新版本"} width={buttonWidth + "px"}/>
                    </vertical>
                </horizontal>
        
            </vertical>
        </frame>
    );

    activity.setSupportActionBar(ui.toolbar);

    ui.emitter.on("create_options_menu", menu => {
        menu.add("日志");
    });
    
    ui.emitter.on("options_item_selected", (e, item) => {
        switch (item.getTitle()) {
            case "日志":
                app.startActivity("console");
                break;
        }
        e.consumed = true;
    });
    
    ui.about1.click(() => {
        let checkPermission = floaty.checkPermission();
        if (!checkPermission) {
            floaty.requestPermission();
            return;
        }
        let info = "" +
            "〇脚本分为实体界面和悬浮窗界面。\n" +
            "〇关于权限问题,默认需要[电话权限][悬浮窗权限]；版本更新需要[储存权限]。\n" +
            "〇模拟点击，需要[无障碍权限]。（设置→辅助功能→无障碍→本APP，不同手机可能会不一样）\n" +
            "☆运行时，悬浮窗需要保持在干燕窝K线图页面。\n"+
            "☆请不要重复启动。\n";
        dialogs.confirm("使用须知", info);
    });
    
    ui.about2.click(() => {
        let checkPermission = floaty.checkPermission();
        if (!checkPermission) {
            floaty.requestPermission();
            return;
        }
        let info = "" +
            "〇版本更新需要先清除旧版本，再获取新版本。\n" ;
        dialogs.confirm("更新说明", info);
    });

    ui.showFloatingTB.click(() => {
        //请求登录接口
        let content = files.read(rootPath + "float.txt");
        if(content == "" || content==null ){
            files.write( rootPath + "float.txt", "1");
            
            let floatingFile = rootPath + "sc/floating.js";
            if (!ensure(floatingFile)) {
                return;
            }
            engines.execScriptFile(floatingFile);
        }else{
            toast("弹框已经打开");
        }
    });
    
    let update = require("./update.js");
    
    ui.updateTB.click(() => {
        let checkPermission = floaty.checkPermission();
        if (!checkPermission) {
            floaty.requestPermission();
            return;
        }
        threads.start(function () {
            let url = "https://gitee.com/gyabjian/autojs/tree/master/";
            update(url + "sc/", rootPath + "sc/", "version.json");
        });
    });
    
    ui.clearTB.click(() => {
        clearScriptTB();
    });
    
    ui.openTB.click(() => {
        toastLog("切换到APP...");
        launch("uni.UNIE9AE111");
    });
    
    function removeFile(fileName) {
        if (files.exists(fileName)) {
            files.remove(fileName);
        }
    }
    
    function clearScriptTB() {
        threads.start(function () {
            files.removeDir(rootPath + "/sc");
            toastLog("清除完成");
        });
    }
    
    function ensure(fileName) {
        let exists = files.exists(fileName);
        if (!exists) {
            dialogs.alert("脚本不存在，请获取最新版本");
        }
        return exists;
    }
    
    function getFloatPermission() {
        engines.execScript("请求悬浮窗权限", "console.show();console.hide();");
    }
    
    function checkFloatPermission() {
        let checkPermission = floaty.checkPermission();
        if (!checkPermission) {
            floaty.requestPermission();
            return;
        }
    }
}

function run(){
    //判断是否登录,登录跳转到页面
    if(isLogin == 1){
        showUI();
    }else{
        //没登录跳转到登录页面
        showLoginUI();
    }
}  
